using Microsoft.AspNetCore.Mvc;
using RAG.Application.Dtos.Knowledge;
using RAG.Application.Services.Interfaces;
using System.Security.Claims;

namespace RAG.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class KnowledgeController : ControllerBase
{
    private readonly IKnowledgeBaseService _knowledgeBaseService;
    private readonly ILogger<KnowledgeController> _logger;

    public KnowledgeController(IKnowledgeBaseService knowledgeBaseService, ILogger<KnowledgeController> logger)
    {
        _knowledgeBaseService = knowledgeBaseService;
        _logger = logger;
    }

    [HttpPost("upload")]
    [RequestSizeLimit(1024 * 1024 * 100)] // 100MB
    [RequestFormLimits(MultipartBodyLengthLimit = 1024 * 1024 * 100)]
    public async Task<ActionResult<DocumentResponseDto>> UploadDocument([FromForm] KnowledgeUploadDto uploadDto)
    {
        try
        {
            if (uploadDto == null)
            {
                _logger.LogWarning("UploadDocument: uploadDto is null");
                return BadRequest(new { message = "表单数据为空" });
            }
            if (string.IsNullOrWhiteSpace(uploadDto.Title))
            {
                return BadRequest(new { message = "标题不能为空" });
            }
            if (uploadDto.File == null || uploadDto.File.Length == 0)
            {
                return BadRequest(new { message = "未选择文件或文件大小为0" });
            }

            var ext = Path.GetExtension(uploadDto.File.FileName).ToLower();
            var allowed = new[] { ".txt", ".docx", ".pdf" }; // 先允许上传 pdf, 处理阶段若未实现解析再标记失败
            if (!allowed.Contains(ext))
            {
                return BadRequest(new { message = $"不支持的文件类型: {ext}, 仅支持: {string.Join(',', allowed)}" });
            }

            var userId = GetCurrentUserId();
            var result = await _knowledgeBaseService.UploadDocumentAsync(uploadDto, userId);

            // 异步处理文档
            _ = Task.Run(async () =>
            {
                try
                {
                    var ok = await _knowledgeBaseService.ProcessDocumentAsync(result.Id);
                    if (!ok)
                    {
                        _logger.LogWarning("文档处理失败: {DocumentId}", result.Id);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "后台处理文档异常: {DocumentId}", result.Id);
                }
            });

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "上传文档失败");
            return BadRequest(new { message = ex.Message, detail = ex.InnerException?.Message });
        }
    }

    [HttpGet]
    public async Task<ActionResult<List<DocumentResponseDto>>> GetDocuments()
    {
        try
        {
            var userId = GetCurrentUserId();
            var documents = await _knowledgeBaseService.GetUserDocumentsAsync(userId);
            return Ok(documents);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<DocumentResponseDto>> GetDocument(Guid id)
    {
        try
        {
            var document = await _knowledgeBaseService.GetDocumentAsync(id);
            if (document == null)
                return NotFound();

            return Ok(document);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpDelete("{id}")]
    public async Task<ActionResult> DeleteDocument(Guid id)
    {
        try
        {
            var userId = GetCurrentUserId();
            await _knowledgeBaseService.DeleteDocumentAsync(id, userId);
            return Ok(new { message = "文档删除成功" });
        }
        catch (UnauthorizedAccessException ex)
        {
            return StatusCode(403, new { message = ex.Message });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpPost("{id}/process")]
    public async Task<ActionResult> ProcessDocument(Guid id)
    {
        try
        {
            var success = await _knowledgeBaseService.ProcessDocumentAsync(id);
            if (success)
                return Ok(new { message = "文档处理成功" });
            else
                return BadRequest(new { message = "文档处理失败" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpGet("statistics")]
    public async Task<ActionResult> GetStatistics()
    {
        try
        {
            var userId = GetCurrentUserId();
            var stats = await _knowledgeBaseService.GetStatisticsAsync(userId);
            return Ok(stats);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 分页获取知识条目
    /// </summary>
    [HttpGet("items")]
    public async Task<ActionResult> GetKnowledgeItems([FromQuery] string? keyword, [FromQuery] Guid? documentId, [FromQuery] string? documentType, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
    {
        try
        {
            var userId = GetCurrentUserId();
            var result = await _knowledgeBaseService.QueryKnowledgeItemsAsync(new RAG.Application.Dtos.Knowledge.KnowledgeItemQuery
            {
                Keyword = keyword,
                DocumentId = documentId,
                DocumentType = documentType,
                Page = page,
                PageSize = pageSize
            }, userId);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 返回当前用户文档简表用于下拉过滤
    /// </summary>
    [HttpGet("documents/simple")]
    public async Task<ActionResult> GetSimpleDocuments()
    {
        try
        {
            var userId = GetCurrentUserId();
            var docs = await _knowledgeBaseService.GetUserDocumentsAsync(userId);
            var simple = docs.Select(d => new { d.Id, d.Title }).OrderByDescending(d => d.Title).ToList();
            return Ok(simple);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 获取单个知识条目详情
    /// </summary>
    [HttpGet("items/{id}")]
    public async Task<ActionResult> GetKnowledgeItem(Guid id)
    {
        try
        {
            var userId = GetCurrentUserId();
            var item = await _knowledgeBaseService.GetKnowledgeItemAsync(id, userId);
            if (item == null) return NotFound();
            return Ok(item);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    private Guid GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (Guid.TryParse(userIdClaim, out var userId))
            return userId;

        // 临时用于测试，实际应该从JWT Token中获取
        return Guid.Parse("00000000-0000-0000-0000-000000000001");
    }
}
